package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func getDemo() {
	apiUrl := "http://127.0.0.1:9000/get"
	data := url.Values{}
	data.Set("name", "扛狼")
	data.Set("age", "18")
	u, err := url.ParseRequestURI(apiUrl)
	if err != nil {
		fmt.Println("url parse failed,err:", err)
		return
	}
	u.RawQuery = data.Encode() // url encode
	fmt.Println(u.String())    // http://127.0.0.1:9000/get?age=18&name=%E6%89%9B%E7%8B%BC
	resp, err := http.Get(u.String())
	if err != nil {
		fmt.Println("get request failed,err:", err)
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get resp failed, err:%v\n", err)
		return
	}
	fmt.Println(string(b))
}

func postDemo() {
	url := "http://127.0.0.1:9000/post"
	content_type := "application/json" // json数据
	data := `{"name":"潇洒哥","age":18}`
	resp, err := http.Post(url, content_type, strings.NewReader(data))
	if err != nil {
		fmt.Println("post request failed,err:", err)
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed,err:", err)
		return
	}
	fmt.Println(string(b))
}

func main() {

	// getDemo()
	postDemo()
	return
	resp, err := http.Get("http://example.com/")
	if err != nil {
		fmt.Println("get request failed,err:", err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Println(string(body))
}
